-- UIMailList
-- Create by chendh
-- 邮件列表

-- UIMailList继承自Layer
UIMailList = class("UIMailList", function()
    return cc.Layer:create();
end);

function UIMailList.create()
    return UIMailList.new();
end

-- 内部函数声明
local resize;
local ITEM_NAME = "item";

-- 构造函数
function UIMailList:ctor()
    self:setName("UIMailList");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/main/SubMapList.csb");
    self:addChild(node);
    self.node = node;

    -- 适配
    resize(self);

    self:initData();

    self:initGrid();

    self:redraw(true);

    -- 显示底部按钮
    self:redrawButtons();

    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();
end

-- 点击响应
function UIMailList:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIMailList");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- 事件响应
function UIMailList:registerEventCallback()
    -- 注册获得焦点的回调
    EventMgr.register("UIMailList", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIMailList" then
            local btNode = findChildByName(self.node, "BT");
            btNode:setVisible(true);

            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM);
        elseif para["lose"] == "UIMailList" then
            local btNode = findChildByName(self.node, "BT");
            btNode:setVisible(false);
        end
    end);

    EventMgr.register("UIMailList", event.UPGRADE_MAILS, function(para)
        self:initData();
        self:initGrid();
        self:redraw();
    end);

    EventMgr.register("UIMailList", event.RECEIVE_MAILS, function(para)
        self:initData();
        self:initGrid();
        self:redraw();
    end);

    EventMgr.register("UIMailList", event.FETCH_MAIL_BONUS, function(para)
        alert(getLocStr("fetch_mail_bonus"));
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            EventMgr.removeAll("UIMailList");
        elseif ev == "enter" then

        end
    end)
end

-- 清空所有的邮件格
function UIMailList:clearAllGrid()
    -- 格子总数
    local totalGridCount = #self.mailList;
    for i = 1, totalGridCount do
        local grid = self.scrollView:getChildByName(ITEM_NAME .. i);
        if grid then
            grid:setVisible(false);
        end
    end
end

-- 绘制界面
function UIMailList:redraw(showEffect)
    local node = self.node;
    -- 设置标题样式
    local titleLabel = findChildByName(node, "TOP/title_bg/text");

    titleLabel:setString(getLocStr("mail_list_title"));
    TextStyleM.setArtWordTitleStyle(titleLabel);

    -- 设置未读提示样式
    local tipLabel = findChildByName(node, "TOP/tip");
    tipLabel:setVisible(true);
    TextStyleM.setTextStyle(tipLabel, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_LIGHT_YELLOW, true, -3, nil, nil, nil, nil, true);
    tipLabel:setString(string.format(getLocStr("mail_list_tip"), MailM.getNewMailNum()));

    -- 绘制邮件列表
    local itemList  = {}
    local itemCount = #self.mailList;
    local index     = 0;

    if not self.mailList or itemCount == 0 then
        cclog("收集邮件信息失败。");
        self:clearAllGrid();
        return;
    end

    for index = 1, itemCount do
        -- 获取邮件格
        local child = self.scrollView:getChildByName(ITEM_NAME .. index);
        if child == nil then
            break;
        end

        -- 插入邮件格列表，用以播放飞入效果
        table.insert(itemList, child);

        -- 绘制邮件信息
        local mailInfo  = self.mailList[index];
        local status    = MailM.checkMailStatus(mailInfo);
        local iconPath  = getMailIconPath(MailM.getMailIcon(mailInfo));

        local bgImg         = child:getChildByName("bg");
        local bgMask        = child:getChildByName("bg_mask");
        local iconImg       = child:getChildByName("icon");
        local nameLabel     = child:getChildByName("name");
        local fromNameLabel = child:getChildByName("from_name");

        -- 邮件图标
        iconImg:loadTexture(iconPath);

        -- 已读邮件显示灰色背景
        if status == MailM.MAIL_STATUS_NEW then
            setGrayTransMode(bgImg, false);
            setGrayTransMode(bgMask, false);
            setGrayTransMode(iconImg, false);
        else
            setGrayTransMode(bgImg, true);
            setGrayTransMode(bgMask, true);
            setGrayTransMode(iconImg, true);
        end

        -- 邮件名称
        TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_ORANGE, true, -3, nil, nil, nil, nil, true);
        nameLabel:setString(MailM.getMailName(mailInfo));

        -- 发件人
        local fromName = mailInfo.from_name;
        -- 如果是系统邮件，那么需要去取系统邮件发件人名称
        if MailM.isSystemBoard(mailInfo) then
            fromName = getLocStr(MailM.MAIL_FROM_DEFAULT);
        elseif MailM.isSystemMail(mailInfo) then
            fromName = getLocStr(fromName);
        end

        TextStyleM.setTextStyle(fromNameLabel, TextStyleM.TEXT_SIZE_TINY, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true, -3);
        TextStyleM.setShadowStyle(fromNameLabel, cc.size(0, -2));
        TextStyleM.setOutlineStyle(fromNameLabel, 1.2, TEXT_OUTLINE_COLOR, true);
        fromNameLabel:setString(string.format(getLocStr("mail_from_name"), fromName));
    end

    if showEffect then
        commonScrollItemFlyIn(itemList);
    end
end

-- 初始化邮件数据
function UIMailList:initData()
    local list = MailM.getAllMailsList();
    local mailList = {};

    for _, mailKey in ipairs(list) do
        table.insert(mailList, MailM.getMailInfo(mailKey));
    end

    self.mailList = mailList;
end

-- 初始化邮件列表
function UIMailList:initGrid()
    local scrollView = findChildByName(self.node, "TOP/scrollview");
    self.scrollView = scrollView;
    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/mail/MailItem.csb");

    -- 获取邮件列表
    local totalNum      = #self.mailList;

    local pageRowNum    = 5;
    local maxColNum     = 1;
    local leftWGap      = 30;
    local topHGap       = 5;
    local bottomHGap    = 10;
    local wGap          = 20;
    local hGap          = 15;
    local iconWidth     = 550;
    local iconHeight    = 110;

    -------------------------------------------------------------------------------
    -- 初始化滚动容器内的单元格（仅针对竖向滚动容器）
    -- @param windowNode    界面节点
    -- @param scrollNode    容器节点
    -- @param itemNode      单元格的节点
    -- @param totalNum      单元格总数
    -- @param pageRowNum    单页可以显示下的行数
    -- @param maxColNum     最大列数
    -- @param wGap          单元格间距(横向) 这里作为最小值使用
    -- @param hGap          单元格间距(纵向)
    -- @param iconWidth     单元格宽度
    -- @param iconHeight    单元格高度
    -- @param topHGap       上方留白
    -- @param bottomHGap    下方留白
    -- @param leftWGap      左右留白  这里作为最小值使用
    -- @param touchEvent    点击事件注册函数
    initScrollGridsVertical(self, scrollView, itemNode, totalNum, pageRowNum, maxColNum, wGap, hGap, iconWidth, iconHeight, topHGap, bottomHGap, leftWGap, self.registerMailItemTouchEvent)
end

-- 邮件点击响应
function UIMailList:registerMailItemTouchEvent(node)
    local image = node:getChildByName("bg");
    local bgMask = node:getChildByName("bg_mask");

    local function onClick(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            -- 1.变小
            local downTime  = 0.25/2;
            local scaleDown = cc.ScaleTo:create(downTime, 0.9);
            node:runAction(scaleDown);
        elseif eventType == ccui.TouchEventType.ended then
            -- 2.变大
            local downTime  = 0.25/2;
            local scaleUp = cc.ScaleTo:create(downTime, 1);
            node:runAction(scaleUp);
        elseif eventType == ccui.TouchEventType.canceled then
            -- 3.变大
            local downTime  = 0.25/2;
            local scaleUp = cc.ScaleTo:create(downTime, 1);
            node:runAction(scaleUp);
        end

        -- 点击时的回调
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            local index = node.index;
            local mailInfo = self.mailList[index];

            if mailInfo == nil then
                return;
            end

            if mailInfo["goto"] then
                -- 跳转提示的邮件
                FormulaM.invoke("LINK_TO_UI", tonumber(mailInfo["goto"]));
                MailM.markView(mailInfo);
                return;
            end

            local title = MailM.getMailName(mailInfo);
            local bonusList = mailInfo.property;
            local msg = MailM.getMailMessage(mailInfo);
            local okText = getLocStr("btn_text_close");

            if MailM.isAlive(mailInfo) and MailM.checkProperty(mailInfo) and MailM.checkMailStatus(mailInfo) == MailM.MAIL_STATUS_NEW then
                okText = getLocStr("take_bonus");
            end

            local function callback()
                if MailM.isAlive(mailInfo) then
                    for k, v in pairs(bonusList) do
                        if v[1] == 2 and v[2] == "life" then
                            local bonusAmount = v[3];
                            local maxLife = ME.user:getMaxLife();
                            local life    = ME.user.dbase:query("life", 0);

                            -- 有活力奖励且活力达到上限时
                            if life >= maxLife or life + bonusAmount > LIMIT_USER_LIFE then
                                alert(getLocStr("cannot_take_life_bonus"));
                                return;
                            end
                        end
                    end
                    MailM.markView(mailInfo);
                end
            end

            local timeMsg = os.date("%Y-%m-%d %H:%M", mailInfo.send_time - TimeM.getTimeOffsetDifference())

            -- 详细内容界面
            require "game/ui/form/mail/UIMailDetail";
            local uiForm = UIMailDetail.create(title, bonusList, callback, msg, okText, { ["timeDesc"] = timeMsg});
            UIMgr.getCurrentScene():addForm(uiForm);
        end
    end

    image:addTouchEventListener(onClick);
    bgMask:addTouchEventListener(onClick);
end

resize = function(self)
    local w = AlignM.frameSize.width;
    local h = AlignM.frameSize.height;

    local scale = w / DESIGN_WIDTH;

    -- 设置scroll的新视口高度
    local scrollview = findChildByName(self.node, "TOP/scrollview");
    local scrollViewSize = scrollview:getContentSize();

    local height = (h / scale) - 420;
    scrollview:setContentSize(scrollViewSize.width, height);

    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");
    AlignM.fitToScreen(node, "bg2");

    -- TOP置于顶部中间并缩放至合适大小
    AlignM.alignToTopCenter(node, "TOP");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 重绘底部按钮
function UIMailList:redrawButtons()
    -- 隐藏没用的按钮
    local btnDungeonEvent = findChildByName(self.node, "BT/btn_dungeon");
    btnDungeonEvent:setVisible(false);

    local btnRankList = findChildByName(self.node, "BT/leaderboard");
    btnRankList:setVisible(false);
end


